<!-- 饼状图 -->
<template>
  <div>
    <div>【问题类别】</div>
    <div ref="pieTarget" class="w-full h-full"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  data: {
    type: Object,
    required: true,
    default: () => []
  }
})

// 动态生成颜色
const generateColors = (count) => {
  const colors = [];
  for (let i = 0; i < count; i++) {
    const hue = (i * 107.508) % 360;
    colors.push(`hsl(${hue}, 70%, 50%)`);
  }
  return colors;
};

// 1. 初始化 echarts 实例
let pieChart = null
const pieTarget = ref(null)

onMounted(() => {
  pieChart = echarts.init(pieTarget.value)
  renderPieChart()
})

// 2. 构建饼图配置
const renderPieChart = () => {
  var options;
  if (props.data.length == 0 ) {  //暂无数据
        options = {
            title: {
                text: '暂无数据',
                x: 'center',
                y: 'center',
                textStyle: {
                  fontSize: 14,
                  fontWeight: 'normal',
                }
              }
              
        }
    } else {
    options = {
      title:{
          text:''
        },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        textStyle: {
          color: '#fff'
        },
        show:false
      },
      series: [
        {
          name: '分类占比',
          type: 'pie',
          radius: ['40%', '70%'], // 内外半径控制环形效果
          center: ['50%', '55%'], // 饼图位置
          avoidLabelOverlap: true, // 关键修复点1：启用标签防重叠
          itemStyle: {
            borderRadius: 4,
            borderColor: '#0a2c5e',
            borderWidth: 2
          },
          label: {
            show: true,
            color: '#fff',
            formatter: '{b|{b}}\n{d}%',
            rich: {
              b: {
                fontSize: 12,
                lineHeight: 20
              }
            }
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16
            }
          },
          labelLine: {
            show: true,
            length: 10,
            length2: 20
          },
          data: props.data.map(item => ({
            name: item.keyString,
            value: item.number
          }))
        }
      ],
      // 动态颜色
      color: generateColors(props.data.length)
    }
  }
  //第二个参数为notMerge 可选，是否不跟之前设置的 option 进行合并，默认为 false (即合并)
  pieChart.setOption(options,true)
}

watch(() => props.data, renderPieChart)
</script>

<style lang="scss" scoped>

</style>